/**
 * @file user_repository.cpp
 * @brief 用户数据访问层实现 - 负责用户数据的CRUD操作和缓存管理
 * @author 29108
 * @date 2025/7/21
 * @version 1.0
 */

#include "core_services/auth_service/user_repository.h"
#include "core_services/auth_service/user_models.h"
#include "common/logger/logger.h"
#include <sstream>
#include <algorithm>
#include <numeric>
#include <cppconn/exception.h>

namespace core_services {
    namespace auth_service {

        // ==================== QueryCondition 实现 ====================

        /**
         * @brief QueryCondition构造函数
         * @param field 字段名
         * @param operator_ 操作符
         * @param value 值
         * @param logic_operator 逻辑操作符
         */
        QueryCondition::QueryCondition(const std::string& field, const std::string& operator_,
                                      const std::string& value, const std::string& logic_operator)
            : field(field)
            , operator_(operator_)
            , value(value)
            , logic_operator(logic_operator) {
        }

        // ==================== QueryOptions 实现 ====================

        /**
         * @brief 添加查询条件
         * @param condition 查询条件
         */
        void QueryOptions::addCondition(const QueryCondition& condition) {
            conditions.push_back(condition);
        }

        /**
         * @brief 构建WHERE子句
         * @return WHERE子句字符串
         */
        std::string QueryOptions::buildWhereClause() const {
            if (conditions.empty()) {
                return "";
            }

            std::stringstream ss;
            ss << " WHERE ";

            for (size_t i = 0; i < conditions.size(); ++i) {
                if (i > 0) {
                    ss << " " << conditions[i].logic_operator << " ";
                }

                ss << conditions[i].field << " " << conditions[i].operator_ << " ";

                // 根据操作符决定是否需要引号
                if (conditions[i].operator_ == "IN") {
                    ss << "(" << conditions[i].value << ")";
                } else if (conditions[i].operator_ == "LIKE") {
                    ss << "'%" << conditions[i].value << "%'";
                } else {
                    ss << "'" << conditions[i].value << "'";
                }
            }

            return ss.str();
        }

        // ==================== BatchOperationResult 实现 ====================

        /**
         * @brief 成功结果构造函数
         * @param affected_rows 影响的行数
         * @param execution_time 执行时间
         */
        BatchOperationResult::BatchOperationResult(int affected_rows, std::chrono::milliseconds execution_time)
            : success(true)
            , affected_rows(affected_rows)
            , execution_time(execution_time) {
        }

        /**
         * @brief 失败结果构造函数
         * @param errors 错误信息列表
         */
        BatchOperationResult::BatchOperationResult(const std::vector<std::string>& errors)
            : success(false)
            , errors(errors) {
        }

        // ==================== UserRepository::Config 实现 ====================

        /**
         * @brief 从配置管理器加载配置
         * @return 用户仓库配置对象
         */
        UserRepository::Config UserRepository::Config::fromConfigManager() {
            auto& config_manager = common::config::ConfigManager::getInstance();

            Config config;
            config.enable_cache = config_manager.get<bool>("user_repository.enable_cache", config.enable_cache);
            config.default_cache_ttl = std::chrono::seconds(config_manager.get<int>("user_repository.default_cache_ttl", config.default_cache_ttl.count()));
            config.user_cache_ttl = std::chrono::seconds(config_manager.get<int>("user_repository.user_cache_ttl", config.user_cache_ttl.count()));
            config.game_data_cache_ttl = std::chrono::seconds(config_manager.get<int>("user_repository.game_data_cache_ttl", config.game_data_cache_ttl.count()));
            config.enable_read_write_split = config_manager.get<bool>("user_repository.enable_read_write_split", config.enable_read_write_split);
            config.max_batch_size = config_manager.get<int>("user_repository.max_batch_size", config.max_batch_size);
            config.enable_async_operations = config_manager.get<bool>("user_repository.enable_async_operations", config.enable_async_operations);
            config.connection_timeout_seconds = config_manager.get<int>("user_repository.connection_timeout_seconds", config.connection_timeout_seconds);
            config.query_timeout_seconds = config_manager.get<int>("user_repository.query_timeout_seconds", config.query_timeout_seconds);

            return config;
        }

        /**
         * @brief 验证配置有效性
         * @return 验证结果，成功返回空字符串
         */
        std::string UserRepository::Config::validate() const {
            if (default_cache_ttl.count() <= 0) {
                return "默认缓存TTL必须大于0";
            }

            if (user_cache_ttl.count() <= 0) {
                return "用户缓存TTL必须大于0";
            }

            if (game_data_cache_ttl.count() <= 0) {
                return "游戏数据缓存TTL必须大于0";
            }

            if (max_batch_size <= 0) {
                return "最大批量操作大小必须大于0";
            }

            if (connection_timeout_seconds <= 0) {
                return "连接超时时间必须大于0";
            }

            if (query_timeout_seconds <= 0) {
                return "查询超时时间必须大于0";
            }

            return ""; // 验证通过
        }

        // ==================== UserRepository 实现 ====================

        /**
         * @brief 构造函数
         * @param config 配置
         * @param mysql_pool MySQL连接池
         * @param redis_pool Redis连接池
         * @param thread_pool 线程池
         */
        UserRepository::UserRepository(const Config& config,
                                      std::shared_ptr<common::database::MySQLPool> mysql_pool,
                                      std::shared_ptr<common::database::RedisPool> redis_pool,
                                      std::shared_ptr<common::thread_pool::ThreadPool> thread_pool)
            : config_(config)
            , mysql_pool_(mysql_pool)
            , redis_pool_(redis_pool)
            , thread_pool_(thread_pool) {

            // 验证配置
            std::string validation_error = config_.validate();
            if (!validation_error.empty()) {
                throw std::invalid_argument("用户仓库配置无效: " + validation_error);
            }

            // 验证必需的依赖
            if (!mysql_pool_) {
                throw std::invalid_argument("MySQL连接池不能为空");
            }

            LOG_INFO("用户数据访问层初始化完成");
            LOG_INFO("- 缓存功能: " + (config_.enable_cache ? std::string("启用") : std::string("禁用")));
            LOG_INFO("- 异步操作: " + (config_.enable_async_operations ? std::string("启用") : std::string("禁用")));
            LOG_INFO("- 读写分离: " + (config_.enable_read_write_split ? std::string("启用") : std::string("禁用")));
        }

        /**
         * @brief 析构函数
         */
        UserRepository::~UserRepository() {
            LOG_INFO("用户数据访问层销毁");
        }

        /**
         * @brief 创建用户
         * @param user_info 用户信息
         * @return 创建成功返回用户ID，失败返回0
         */
        int64_t UserRepository::createUser(const CoreUserInfo& user_info) {
            try {
                // 验证用户信息
                std::string validation_error = user_info.validate();
                if (!validation_error.empty()) {
                    LOG_ERROR("用户信息验证失败: " + validation_error);
                    return 0;
                }

                // 构建插入SQL
                auto [sql, params] = buildUserInsertSQL(user_info);

                LOG_INFO("创建用户 - SQL: " + sql);
                LOG_INFO("创建用户 - 参数数量: " + std::to_string(params.size()));
                for (size_t i = 0; i < params.size(); ++i) {
                    LOG_INFO("创建用户 - 参数[" + std::to_string(i) + "]: " + params[i]);
                }

                // 执行插入操作
                LOG_INFO("创建用户 - 准备获取MySQL连接");
                LOG_INFO("创建用户 - 连接池状态 - 活跃: " + std::to_string(mysql_pool_->getActiveConnections()) +
                        ", 空闲: " + std::to_string(mysql_pool_->getIdleConnections()) +
                        ", 总计: " + std::to_string(mysql_pool_->getTotalConnections()));

                auto start_time = std::chrono::steady_clock::now();

                // 使用 RAII 连接管理器，确保连接自动归还
                common::database::MySQLConnectionGuard conn_guard(*mysql_pool_);
                auto mysql_conn = conn_guard.get();

                auto end_time = std::chrono::steady_clock::now();
                auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(end_time - start_time);

                LOG_INFO("创建用户 - 获取MySQL连接耗时: " + std::to_string(duration.count()) + "ms");

                if (!mysql_conn) {
                    LOG_ERROR("无法获取MySQL连接");
                    return 0;
                }

                auto stmt = mysql_conn->prepareStatement(sql);
                for (size_t i = 0; i < params.size(); ++i) {
                    stmt->setString(i + 1, params[i]);
                }

                LOG_INFO("创建用户 - 准备执行SQL插入");
                int affected_rows = stmt->executeUpdate();
                LOG_INFO("创建用户 - SQL执行完成，影响行数: " + std::to_string(affected_rows));
                if (affected_rows > 0) {
                    // 获取插入的用户ID
                    auto result_stmt = mysql_conn->prepareStatement("SELECT LAST_INSERT_ID()");
                    auto result_set = result_stmt->executeQuery();

                    int64_t user_id = 0;
                    if (result_set->next()) {
                        user_id = result_set->getInt64(1);
                    }

                    users_created_++;
                    LOG_INFO("用户创建成功，用户ID: " + std::to_string(user_id));

                    // 清除相关缓存
                    if (config_.enable_cache && redis_pool_) {
                        clearUserCache(user_id);
                    }

                    LOG_INFO("创建用户 - 连接即将归还到连接池");
                    return user_id;
                }

                LOG_ERROR("用户创建失败，SQL执行无影响行数");
                return 0;
            } catch (const sql::SQLException& e) {
                LOG_ERROR("创建用户时发生SQL异常: " + std::string(e.what()));
                LOG_ERROR("SQL错误码: " + std::to_string(e.getErrorCode()));
                LOG_ERROR("SQL状态: " + std::string(e.getSQLState()));
                return 0;
            } catch (const std::exception& e) {
                LOG_ERROR("创建用户时发生异常: " + std::string(e.what()));
                return 0;
            }
        }

        /**
         * @brief 根据用户ID查找用户
         * @param user_id 用户ID
         * @param use_cache 是否使用缓存
         * @return 用户信息，未找到返回nullopt
         */
        std::optional<CoreUserInfo> UserRepository::findUserById(int64_t user_id, bool use_cache) {
            try {
                queries_executed_++;

                // 尝试从缓存获取
                if (use_cache && config_.enable_cache && redis_pool_) {
                    std::string cache_key = generateUserCacheKey(user_id);
                    auto cached_user = getUserFromCache(cache_key);
                    if (cached_user.has_value()) {
                        cache_hits_++;
                        return cached_user;
                    }
                    cache_misses_++;
                }

                // 从数据库查询
                std::string sql = R"(
                    SELECT user_id, username, email, password_hash, salt, nickname, avatar_url,
                           status, online_status, created_at, updated_at, last_login_at,
                           last_login_ip, login_attempts, locked_until
                    FROM users
                    WHERE user_id = ? AND status != 4
                )";

                auto user = queryUserFromDB(sql, {std::to_string(user_id)});

                // 如果找到用户，加载角色和元数据
                if (user.has_value()) {
                    loadUserRoles(user.value());
                    loadUserMetadata(user.value());

                    // 存入缓存
                    if (use_cache && config_.enable_cache && redis_pool_) {
                        std::string cache_key = generateUserCacheKey(user_id);
                        setUserToCache(cache_key, user.value(), config_.user_cache_ttl);
                    }
                }

                return user;
            } catch (const std::exception& e) {
                LOG_ERROR("根据用户ID查找用户时发生异常: " + std::string(e.what()));
                return std::nullopt;
            }
        }

        /**
         * @brief 根据用户名查找用户
         * @param username 用户名
         * @param use_cache 是否使用缓存
         * @return 用户信息，未找到返回nullopt
         */
        std::optional<CoreUserInfo> UserRepository::findUserByUsername(const std::string& username, bool use_cache) {
            try {
                LOG_INFO("UserRepository::findUserByUsername 开始查找用户: " + username);
                queries_executed_++;

                // 尝试从缓存获取
                bool cache_available = true;
                if (use_cache && config_.enable_cache && redis_pool_) {
                    std::string cache_key = generateUsernameCacheKey(username);
                    try {
                        auto cached_user = getUserFromCache(cache_key);
                        if (cached_user.has_value()) {
                            cache_hits_++;
                            LOG_INFO("从缓存获取用户成功: " + username);
                            return cached_user;
                        }
                        cache_misses_++;
                        LOG_DEBUG("缓存未命中，将查询数据库: " + username);
                    } catch (const std::exception& e) {
                        LOG_WARNING("缓存查询失败，将直接查询数据库: " + std::string(e.what()));
                        cache_available = false;
                    }
                }

                // 从数据库查询
                LOG_INFO("从数据库查询用户: " + username);

                // 首先测试数据库连接和表是否存在
                try {
                    common::database::MySQLConnectionGuard test_guard(*mysql_pool_);
                    auto test_conn = test_guard.get();
                    if (test_conn) {
                        auto test_stmt = test_conn->prepareStatement("SELECT COUNT(*) FROM users");
                        auto test_result = test_stmt->executeQuery();
                        if (test_result->next()) {
                            int total_users = test_result->getInt(1);
                            LOG_INFO("数据库连接正常，users表中共有 " + std::to_string(total_users) + " 个用户");
                        }
                    }
                } catch (const std::exception& e) {
                    LOG_ERROR("数据库连接测试失败: " + std::string(e.what()));
                }

                std::string sql = R"(
                    SELECT user_id, username, email, password_hash, salt, nickname, avatar_url,
                           status, online_status, created_at, updated_at, last_login_at,
                           last_login_ip, login_attempts, locked_until
                    FROM users
                    WHERE username = ? AND status != 4
                )";

                auto user = queryUserFromDB(sql, {username});
                LOG_INFO("数据库查询结果: " + std::string(user.has_value() ? "找到用户" : "用户不存在"));

                // 如果找到用户，加载角色和元数据
                if (user.has_value()) {
                    try {
                        loadUserRoles(user.value());
                        loadUserMetadata(user.value());
                        LOG_DEBUG("用户角色和元数据加载完成: " + username);
                    } catch (const std::exception& e) {
                        LOG_WARNING("加载用户角色和元数据失败: " + std::string(e.what()));
                        // 继续处理，不因为角色加载失败而中断
                    }

                    // 存入缓存
                    if (use_cache && config_.enable_cache && redis_pool_ && cache_available) {
                        try {
                            std::string cache_key = generateUsernameCacheKey(username);
                            bool cache_success = setUserToCache(cache_key, user.value(), config_.user_cache_ttl);

                            if (cache_success) {
                                // 同时缓存用户ID索引
                                std::string user_id_cache_key = generateUserCacheKey(user->user_id);
                                setUserToCache(user_id_cache_key, user.value(), config_.user_cache_ttl);
                                LOG_DEBUG("用户信息已缓存: " + username);
                            }
                        } catch (const std::exception& e) {
                            LOG_WARNING("缓存用户信息失败: " + std::string(e.what()));
                            // 缓存失败不影响返回结果
                        }
                    }
                }

                return user;
            } catch (const std::exception& e) {
                LOG_ERROR("根据用户名查找用户时发生异常: " + std::string(e.what()));
                return std::nullopt;
            }
        }

        /**
         * @brief 更新用户登录信息（仅更新登录相关字段，避免验证问题）
         * @param user_id 用户ID
         * @param login_attempts 登录尝试次数
         * @param locked_until 锁定截止时间
         * @param last_login_at 最后登录时间
         * @param last_login_ip 最后登录IP
         * @param online_status 在线状态
         * @return 更新成功返回true
         */
        bool UserRepository::updateUserLoginInfo(int64_t user_id, int login_attempts,
                                                 std::optional<std::chrono::system_clock::time_point> locked_until,
                                                 std::optional<std::chrono::system_clock::time_point> last_login_at,
                                                 const std::string& last_login_ip,
                                                 OnlineStatus online_status) {
            try {
                if (!mysql_pool_) {
                    return false;
                }

                // 使用 RAII 连接管理器，确保连接自动归还
                common::database::MySQLConnectionGuard conn_guard(*mysql_pool_);
                auto mysql_conn = conn_guard.get();
                if (!mysql_conn) {
                    LOG_ERROR("无法获取MySQL连接");
                    return false;
                }

                std::string sql = R"(
                    UPDATE users SET
                        login_attempts = ?,
                        locked_until = ?,
                        last_login_at = ?,
                        last_login_ip = ?,
                        online_status = ?,
                        updated_at = CURRENT_TIMESTAMP
                    WHERE user_id = ?
                )";

                auto stmt = mysql_conn->prepareStatement(sql);
                stmt->setInt(1, login_attempts);

                if (locked_until.has_value()) {
                    stmt->setString(2, timePointToMySQLDateTime(locked_until.value()));
                } else {
                    stmt->setNull(2, sql::DataType::TIMESTAMP);
                }

                if (last_login_at.has_value()) {
                    stmt->setString(3, timePointToMySQLDateTime(last_login_at.value()));
                } else {
                    stmt->setNull(3, sql::DataType::TIMESTAMP);
                }

                stmt->setString(4, last_login_ip);
                stmt->setInt(5, static_cast<int>(online_status));
                stmt->setInt64(6, user_id);

                int affected_rows = stmt->executeUpdate();
                if (affected_rows > 0) {
                    LOG_DEBUG("用户登录信息更新成功，用户ID: " + std::to_string(user_id));

                    // 清除相关缓存
                    if (config_.enable_cache && redis_pool_) {
                        clearUserCache(user_id);
                    }

                    return true;
                }

                LOG_WARNING("用户登录信息更新失败，无影响行数，用户ID: " + std::to_string(user_id));
                return false;
            } catch (const std::exception& e) {
                LOG_ERROR("更新用户登录信息时发生异常: " + std::string(e.what()));
                return false;
            }
        }

        /**
         * @brief 更新用户信息
         * @param user_info 用户信息
         * @return 更新成功返回true
         */
        bool UserRepository::updateUser(const CoreUserInfo& user_info) {
            try {
                // 验证用户信息
                std::string validation_error = user_info.validate();
                if (!validation_error.empty()) {
                    LOG_ERROR("用户信息验证失败: " + validation_error);
                    return false;
                }

                // 构建更新SQL
                auto [sql, params] = buildUserUpdateSQL(user_info);

                // 执行更新操作
                int affected_rows = executeUpdate(sql, params);
                if (affected_rows > 0) {
                    users_updated_++;
                    LOG_INFO("用户信息更新成功，用户ID: " + std::to_string(user_info.user_id));

                    // 更新角色信息
                    updateUserRoles(user_info);

                    // 更新元数据
                    updateUserMetadata(user_info);

                    // 清除相关缓存
                    if (config_.enable_cache && redis_pool_) {
                        clearUserCache(user_info.user_id);
                    }

                    return true;
                }

                LOG_WARNING("用户信息更新失败，无影响行数，用户ID: " + std::to_string(user_info.user_id));
                return false;
            } catch (const std::exception& e) {
                LOG_ERROR("更新用户信息时发生异常: " + std::string(e.what()));
                return false;
            }
        }

        /**
         * @brief 根据邮箱查找用户
         * @param email 邮箱
         * @param use_cache 是否使用缓存
         * @return 用户信息，未找到返回nullopt
         */
        std::optional<CoreUserInfo> UserRepository::findUserByEmail(const std::string& email, bool use_cache) {
            try {
                queries_executed_++;

                // 尝试从缓存获取
                if (use_cache && config_.enable_cache && redis_pool_) {
                    std::string cache_key = generateEmailCacheKey(email);
                    auto cached_user = getUserFromCache(cache_key);
                    if (cached_user.has_value()) {
                        cache_hits_++;
                        return cached_user;
                    }
                    cache_misses_++;
                }

                // 从数据库查询
                std::string sql = R"(
                    SELECT user_id, username, email, password_hash, salt, nickname, avatar_url,
                           status, online_status, created_at, updated_at, last_login_at,
                           last_login_ip, login_attempts, locked_until
                    FROM users
                    WHERE email = ? AND status != 4
                )";

                auto user = queryUserFromDB(sql, {email});

                // 如果找到用户，加载角色和元数据
                if (user.has_value()) {
                    loadUserRoles(user.value());
                    loadUserMetadata(user.value());

                    // 存入缓存
                    if (use_cache && config_.enable_cache && redis_pool_) {
                        std::string cache_key = generateEmailCacheKey(email);
                        setUserToCache(cache_key, user.value(), config_.user_cache_ttl);

                        // 同时缓存用户ID索引
                        std::string user_id_cache_key = generateUserCacheKey(user->user_id);
                        setUserToCache(user_id_cache_key, user.value(), config_.user_cache_ttl);
                    }
                }

                return user;
            } catch (const std::exception& e) {
                LOG_ERROR("根据邮箱查找用户时发生异常: " + std::string(e.what()));
                return std::nullopt;
            }
        }

        /**
         * @brief 获取用户游戏数据
         * @param user_id 用户ID
         * @param game_type 游戏类型
         * @param use_cache 是否使用缓存
         * @return 游戏用户数据，未找到返回nullopt
         */
        std::optional<GameUserData> UserRepository::getUserGameData(int64_t user_id, GameType game_type, bool use_cache) {
            try {
                queries_executed_++;

                // 尝试从缓存获取
                if (use_cache && config_.enable_cache && redis_pool_) {
                    std::string cache_key = generateGameDataCacheKey(user_id, game_type);
                    auto cached_data = getGameDataFromCache(cache_key);
                    if (cached_data.has_value()) {
                        cache_hits_++;
                        return cached_data;
                    }
                    cache_misses_++;
                }

                // 从数据库查询
                std::string sql = R"(
                    SELECT user_id, game_type, level, experience, coins, gems, total_games,
                           wins, losses, draws, total_playtime_seconds, best_score,
                           last_played_at, created_at, updated_at
                    FROM game_user_data
                    WHERE user_id = ? AND game_type = ?
                )";

                auto game_data = queryGameDataFromDB(sql, {std::to_string(user_id), std::to_string(static_cast<int>(game_type))});

                // 如果找到数据，加载自定义数据和成就
                if (game_data.has_value()) {
                    loadGameUserCustomData(game_data.value());
                    loadGameUserAchievements(game_data.value());

                    // 存入缓存
                    if (use_cache && config_.enable_cache && redis_pool_) {
                        std::string cache_key = generateGameDataCacheKey(user_id, game_type);
                        setGameDataToCache(cache_key, game_data.value(), config_.game_data_cache_ttl);
                    }
                }

                return game_data;
            } catch (const std::exception& e) {
                LOG_ERROR("获取用户游戏数据时发生异常: " + std::string(e.what()));
                return std::nullopt;
            }
        }

        // ==================== 内部方法实现 ====================

        /**
         * @brief 生成用户缓存键
         * @param user_id 用户ID
         * @return 缓存键
         */
        std::string UserRepository::generateUserCacheKey(int64_t user_id) {
            return "user:id:" + std::to_string(user_id);
        }

        /**
         * @brief 生成用户名缓存键
         * @param username 用户名
         * @return 缓存键
         */
        std::string UserRepository::generateUsernameCacheKey(const std::string& username) {
            return "user:username:" + username;
        }

        /**
         * @brief 生成邮箱缓存键
         * @param email 邮箱
         * @return 缓存键
         */
        std::string UserRepository::generateEmailCacheKey(const std::string& email) {
            return "user:email:" + email;
        }

        /**
         * @brief 生成游戏数据缓存键
         * @param user_id 用户ID
         * @param game_type 游戏类型
         * @return 缓存键
         */
        std::string UserRepository::generateGameDataCacheKey(int64_t user_id, GameType game_type) {
            return "game:data:user:" + std::to_string(user_id) + ":type:" + std::to_string(static_cast<int>(game_type));
        }

        /**
         * @brief 从缓存获取用户信息
         * @param cache_key 缓存键
         * @return 用户信息，未找到返回nullopt
         */
        std::optional<CoreUserInfo> UserRepository::getUserFromCache(const std::string& cache_key) {
            try {
                if (!redis_pool_) {
                    LOG_DEBUG("Redis连接池未初始化，跳过缓存查询");
                    return std::nullopt;
                }

                // 使用 RAII 连接管理器，确保连接自动归还
                common::database::RedisConnectionGuard conn_guard(*redis_pool_);
                auto redis_conn = conn_guard.get();
                if (!redis_conn) {
                    LOG_WARNING("无法获取Redis连接，跳过缓存查询: " + cache_key);
                    return std::nullopt;
                }

                std::string user_data = redis_conn->get(cache_key);
                if (user_data.empty()) {
                    LOG_DEBUG("缓存中未找到数据: " + cache_key);
                    return std::nullopt;
                }

                LOG_DEBUG("从缓存获取到用户数据: " + cache_key);
                auto json_data = nlohmann::json::parse(user_data);
                return CoreUserInfo::fromJson(json_data);

            } catch (const std::exception& e) {
                LOG_ERROR("从缓存获取用户信息时发生异常: " + std::string(e.what()) + ", cache_key: " + cache_key);
                // 缓存异常时不应该阻止数据库查询
                return std::nullopt;
            }
        }

        /**
         * @brief 将用户信息存入缓存
         * @param cache_key 缓存键
         * @param user_info 用户信息
         * @param ttl 缓存TTL
         * @return 存储成功返回true
         */
        bool UserRepository::setUserToCache(const std::string& cache_key, const CoreUserInfo& user_info, std::chrono::seconds ttl) {
            try {
                if (!redis_pool_) {
                    return false;
                }

                // 使用 RAII 连接管理器，确保连接自动归还
                common::database::RedisConnectionGuard conn_guard(*redis_pool_);
                auto redis_conn = conn_guard.get();
                if (!redis_conn) {
                    return false;
                }

                std::string user_data = user_info.toJson().dump();
                redis_conn->set(cache_key, user_data, static_cast<int>(ttl.count()));

                return true;

            } catch (const std::exception& e) {
                LOG_ERROR("将用户信息存入缓存时发生异常: " + std::string(e.what()));
                return false;
            }
        }

        /**
         * @brief 从缓存获取游戏数据
         * @param cache_key 缓存键
         * @return 游戏数据，未找到返回nullopt
         */
        std::optional<GameUserData> UserRepository::getGameDataFromCache(const std::string& cache_key) {
            try {
                if (!redis_pool_) {
                    return std::nullopt;
                }

                // 使用 RAII 连接管理器，确保连接自动归还
                common::database::RedisConnectionGuard conn_guard(*redis_pool_);
                auto redis_conn = conn_guard.get();
                if (!redis_conn) {
                    return std::nullopt;
                }

                std::string game_data = redis_conn->get(cache_key);
                if (game_data.empty()) {
                    return std::nullopt;
                }

                auto json_data = nlohmann::json::parse(game_data);
                return GameUserData::fromJson(json_data);

            } catch (const std::exception& e) {
                LOG_ERROR("从缓存获取游戏数据时发生异常: " + std::string(e.what()));
                return std::nullopt;
            }
        }

        /**
         * @brief 将游戏数据存入缓存
         * @param cache_key 缓存键
         * @param game_data 游戏数据
         * @param ttl 缓存TTL
         * @return 存储成功返回true
         */
        bool UserRepository::setGameDataToCache(const std::string& cache_key, const GameUserData& game_data, std::chrono::seconds ttl) {
            try {
                if (!redis_pool_) {
                    return false;
                }

                // 使用 RAII 连接管理器，确保连接自动归还
                common::database::RedisConnectionGuard conn_guard(*redis_pool_);
                auto redis_conn = conn_guard.get();
                if (!redis_conn) {
                    return false;
                }

                std::string data = game_data.toJson().dump();
                redis_conn->set(cache_key, data, static_cast<int>(ttl.count()));

                return true;

            } catch (const std::exception& e) {
                LOG_ERROR("将游戏数据存入缓存时发生异常: " + std::string(e.what()));
                return false;
            }
        }

        /**
         * @brief 从数据库查询用户
         * @param sql SQL语句
         * @param params 参数列表
         * @return 用户信息，未找到返回nullopt
         */
        std::optional<CoreUserInfo> UserRepository::queryUserFromDB(const std::string& sql, const std::vector<std::string>& params) {
            const int max_retries = 3;

            for (int retry = 0; retry < max_retries; retry++) {
                try {
                    LOG_INFO("queryUserFromDB 开始执行SQL查询，尝试次数: " + std::to_string(retry + 1));

                    // 使用 RAII 连接管理器
                    common::database::MySQLConnectionGuard conn_guard(*mysql_pool_);
                    auto mysql_conn = conn_guard.get();
                    if (!mysql_conn) {
                        LOG_ERROR("无法获取MySQL连接，尝试次数: " + std::to_string(retry + 1));
                        if (retry < max_retries - 1) {
                            std::this_thread::sleep_for(std::chrono::milliseconds(100 * (retry + 1)));
                            continue;
                        }
                        return std::nullopt;
                    }
                    LOG_INFO("成功获取MySQL连接");

                    LOG_INFO("准备SQL语句");
                    auto stmt = mysql_conn->prepareStatement(sql);
                    for (size_t i = 0; i < params.size(); ++i) {
                        stmt->setString(i + 1, params[i]);
                        LOG_INFO("设置参数 " + std::to_string(i + 1) + ": " + params[i]);
                    }

                    LOG_INFO("执行SQL查询");
                    auto result_set = stmt->executeQuery();
                    if (result_set->next()) {
                        LOG_INFO("查询到结果，构建用户对象");
                        return buildUserFromResultSet(result_set);
                    }

                    LOG_INFO("查询无结果 - 用户不存在");
                    return std::nullopt;

                } catch (const std::exception& e) {
                    LOG_ERROR("从数据库查询用户时发生异常，尝试次数: " + std::to_string(retry + 1) + ", 错误: " + std::string(e.what()));

                    if (retry < max_retries - 1) {
                        LOG_INFO("等待 " + std::to_string(200 * (retry + 1)) + "ms 后重试...");
                        std::this_thread::sleep_for(std::chrono::milliseconds(200 * (retry + 1)));
                        continue;
                    } else {
                        LOG_ERROR("所有重试均失败，查询用户失败");
                    }
                }
            }

            LOG_ERROR("经过 " + std::to_string(max_retries) + " 次重试后仍无法查询用户");
            return std::nullopt;
        }

        /**
         * @brief 从数据库查询游戏数据
         * @param sql SQL语句
         * @param params 参数列表
         * @return 游戏数据，未找到返回nullopt
         */
        std::optional<GameUserData> UserRepository::queryGameDataFromDB(const std::string& sql, const std::vector<std::string>& params) {
            try {
                LOG_INFO("queryGameDataFromDB 开始执行");
                LOG_INFO("SQL: " + sql);
                for (size_t i = 0; i < params.size(); ++i) {
                    LOG_INFO("参数 " + std::to_string(i + 1) + ": " + params[i]);
                }

                // 使用 RAII 连接管理器
                common::database::MySQLConnectionGuard conn_guard(*mysql_pool_);
                auto mysql_conn = conn_guard.get();
                if (!mysql_conn) {
                    LOG_ERROR("无法获取MySQL连接");
                    return std::nullopt;
                }

                LOG_INFO("成功获取MySQL连接");

                auto stmt = mysql_conn->prepareStatement(sql);
                LOG_INFO("SQL语句准备完成");

                for (size_t i = 0; i < params.size(); ++i) {
                    stmt->setString(i + 1, params[i]);
                    LOG_INFO("设置参数 " + std::to_string(i + 1) + ": " + params[i]);
                }

                LOG_INFO("开始执行查询");
                auto result_set = stmt->executeQuery();
                LOG_INFO("查询执行完成");

                if (result_set->next()) {
                    LOG_INFO("找到游戏数据，开始构建对象");
                    auto game_data = buildGameDataFromResultSet(result_set);
                    LOG_INFO("游戏数据对象构建完成");
                    return game_data;
                }

                LOG_INFO("未找到游戏数据");
                return std::nullopt;

            } catch (const std::exception& e) {
                LOG_ERROR("从数据库查询游戏数据时发生异常: " + std::string(e.what()));
                return std::nullopt;
            }
        }

        /**
         * @brief 执行数据库更新操作
         * @param sql SQL语句
         * @param params 参数列表
         * @return 影响的行数
         */
        int UserRepository::executeUpdate(const std::string& sql, const std::vector<std::string>& params) {
            try {
                // 使用 RAII 连接管理器
                common::database::MySQLConnectionGuard conn_guard(*mysql_pool_);
                auto mysql_conn = conn_guard.get();
                if (!mysql_conn) {
                    LOG_ERROR("无法获取MySQL连接");
                    return 0;
                }

                auto stmt = mysql_conn->prepareStatement(sql);
                for (size_t i = 0; i < params.size(); ++i) {
                    // 处理 NULL 值
                    if (params[i] == "NULL") {
                        stmt->setNull(i + 1, sql::DataType::UNKNOWN);
                    } else {
                        stmt->setString(i + 1, params[i]);
                    }
                }

                return stmt->executeUpdate();

            } catch (const std::exception& e) {
                LOG_ERROR("执行数据库更新操作时发生异常: " + std::string(e.what()));
                return 0;
            }
        }

        /**
         * @brief 构建用户插入SQL
         * @param user_info 用户信息
         * @return SQL语句和参数
         */
        std::pair<std::string, std::vector<std::string>> UserRepository::buildUserInsertSQL(const CoreUserInfo& user_info) {
            std::string sql = R"(
                INSERT INTO users (username, email, password_hash, salt, nickname, avatar_url,
                                 status, online_status)
                VALUES (?, ?, ?, ?, ?, ?, ?, ?)
            )";

            std::vector<std::string> params;
            params.push_back(user_info.username);
            params.push_back(user_info.email);
            params.push_back(user_info.password_hash);
            params.push_back(user_info.salt);
            params.push_back(user_info.nickname);
            params.push_back(user_info.avatar_url);
            params.push_back(std::to_string(static_cast<int>(user_info.status)));
            params.push_back(std::to_string(static_cast<int>(user_info.online_status)));
            // 让数据库自动设置 created_at 和 updated_at

            return std::make_pair(sql, params);
        }

        /**
         * @brief 构建用户更新SQL
         * @param user_info 用户信息
         * @return SQL语句和参数
         */
        std::pair<std::string, std::vector<std::string>> UserRepository::buildUserUpdateSQL(const CoreUserInfo& user_info) {
            std::vector<std::string> set_clauses;
            std::vector<std::string> params;

            // 基本字段（总是更新）
            set_clauses.push_back("username = ?");
            params.push_back(user_info.username);

            set_clauses.push_back("email = ?");
            params.push_back(user_info.email);

            set_clauses.push_back("password_hash = ?");
            params.push_back(user_info.password_hash);

            set_clauses.push_back("salt = ?");
            params.push_back(user_info.salt);

            set_clauses.push_back("nickname = ?");
            params.push_back(user_info.nickname);

            set_clauses.push_back("avatar_url = ?");
            params.push_back(user_info.avatar_url);

            set_clauses.push_back("status = ?");
            params.push_back(std::to_string(static_cast<int>(user_info.status)));

            set_clauses.push_back("online_status = ?");
            params.push_back(std::to_string(static_cast<int>(user_info.online_status)));

            set_clauses.push_back("updated_at = ?");
            params.push_back(timePointToMySQLDateTime(user_info.updated_at));

            // 可选字段（只在有值时更新）
            if (user_info.last_login_at.has_value()) {
                set_clauses.push_back("last_login_at = ?");
                params.push_back(timePointToMySQLDateTime(user_info.last_login_at.value()));
            }

            if (!user_info.last_login_ip.empty()) {
                set_clauses.push_back("last_login_ip = ?");
                params.push_back(user_info.last_login_ip);
            }

            set_clauses.push_back("login_attempts = ?");
            params.push_back(std::to_string(user_info.login_attempts));

            if (user_info.locked_until.has_value()) {
                set_clauses.push_back("locked_until = ?");
                params.push_back(timePointToMySQLDateTime(user_info.locked_until.value()));
            }

            // 构建完整的 SQL
            std::string sql = "UPDATE users SET " +
                             std::accumulate(set_clauses.begin(), set_clauses.end(), std::string(),
                                           [](const std::string& a, const std::string& b) {
                                               return a.empty() ? b : a + ", " + b;
                                           }) +
                             " WHERE user_id = ?";

            // 添加 WHERE 条件参数
            params.push_back(std::to_string(user_info.user_id));

            return std::make_pair(sql, params);
        }

        /**
         * @brief 从结果集构建用户信息
         * @param result_set 结果集
         * @return 用户信息
         */
        CoreUserInfo UserRepository::buildUserFromResultSet(sql::ResultSet* result_set) {
            CoreUserInfo user_info;

            try {
                user_info.user_id = result_set->getInt64("user_id");
                user_info.username = result_set->getString("username");
                user_info.email = result_set->getString("email");
                user_info.password_hash = result_set->getString("password_hash");
                user_info.salt = result_set->getString("salt");
                user_info.nickname = result_set->getString("nickname");
                user_info.avatar_url = result_set->getString("avatar_url");
                user_info.status = static_cast<UserStatus>(result_set->getInt("status"));
                user_info.online_status = static_cast<OnlineStatus>(result_set->getInt("online_status"));

                // 安全处理时间戳字段
                std::string created_at_str = result_set->getString("created_at");
                if (!created_at_str.empty() && created_at_str != "NULL") {
                    try {
                        user_info.created_at = timestampToTimePoint(std::stoll(created_at_str));
                    } catch (const std::exception& e) {
                        LOG_WARNING("解析created_at时间戳失败: " + created_at_str + ", 错误: " + std::string(e.what()));
                        user_info.created_at = std::chrono::system_clock::now(); // 使用当前时间作为默认值
                    }
                } else {
                    user_info.created_at = std::chrono::system_clock::now();
                }

                std::string updated_at_str = result_set->getString("updated_at");
                if (!updated_at_str.empty() && updated_at_str != "NULL") {
                    try {
                        user_info.updated_at = timestampToTimePoint(std::stoll(updated_at_str));
                    } catch (const std::exception& e) {
                        LOG_WARNING("解析updated_at时间戳失败: " + updated_at_str + ", 错误: " + std::string(e.what()));
                        user_info.updated_at = std::chrono::system_clock::now(); // 使用当前时间作为默认值
                    }
                } else {
                    user_info.updated_at = std::chrono::system_clock::now();
                }

                // 处理可选字段
                std::string last_login_str = result_set->getString("last_login_at");
                if (!last_login_str.empty() && last_login_str != "NULL") {
                    try {
                        user_info.last_login_at = timestampToTimePoint(std::stoll(last_login_str));
                    } catch (const std::exception& e) {
                        LOG_WARNING("解析last_login_at时间戳失败: " + last_login_str + ", 错误: " + std::string(e.what()));
                        // last_login_at 保持为 nullopt
                    }
                }

                user_info.last_login_ip = result_set->getString("last_login_ip");
                user_info.login_attempts = result_set->getInt("login_attempts");

                std::string locked_until_str = result_set->getString("locked_until");
                if (!locked_until_str.empty() && locked_until_str != "NULL") {
                    try {
                        user_info.locked_until = timestampToTimePoint(std::stoll(locked_until_str));
                    } catch (const std::exception& e) {
                        LOG_WARNING("解析locked_until时间戳失败: " + locked_until_str + ", 错误: " + std::string(e.what()));
                        // locked_until 保持为 nullopt
                    }
                }

                return user_info;

            } catch (const std::exception& e) {
                LOG_ERROR("构建用户对象时发生异常: " + std::string(e.what()));
                // 返回一个默认的用户对象，避免程序崩溃
                CoreUserInfo default_user;
                default_user.user_id = -1; // 标记为无效用户
                default_user.created_at = std::chrono::system_clock::now();
                default_user.updated_at = std::chrono::system_clock::now();
                return default_user;
            }
        }

        /**
         * @brief 从结果集构建游戏数据
         * @param result_set 结果集
         * @return 游戏数据
         */
        GameUserData UserRepository::buildGameDataFromResultSet(sql::ResultSet* result_set) {
            GameUserData game_data;

            try {
                game_data.user_id = result_set->getInt64("user_id");
                game_data.game_type = static_cast<GameType>(result_set->getInt("game_type"));
                game_data.level = result_set->getInt("level");
                game_data.experience = result_set->getInt64("experience");
                game_data.coins = result_set->getInt64("coins");
                game_data.gems = result_set->getInt64("gems");
                game_data.total_games = result_set->getInt("total_games");
                game_data.wins = result_set->getInt("wins");
                game_data.losses = result_set->getInt("losses");
                game_data.draws = result_set->getInt("draws");
                game_data.total_playtime_seconds = result_set->getInt64("total_playtime_seconds");
                game_data.best_score = result_set->getInt64("best_score");

                // 安全处理时间戳字段
                std::string created_at_str = result_set->getString("created_at");
                if (!created_at_str.empty() && created_at_str != "NULL") {
                    try {
                        game_data.created_at = timestampToTimePoint(std::stoll(created_at_str));
                    } catch (const std::exception& e) {
                        LOG_WARNING("解析游戏数据created_at时间戳失败: " + created_at_str + ", 错误: " + std::string(e.what()));
                        game_data.created_at = std::chrono::system_clock::now();
                    }
                } else {
                    game_data.created_at = std::chrono::system_clock::now();
                }

                std::string updated_at_str = result_set->getString("updated_at");
                if (!updated_at_str.empty() && updated_at_str != "NULL") {
                    try {
                        game_data.updated_at = timestampToTimePoint(std::stoll(updated_at_str));
                    } catch (const std::exception& e) {
                        LOG_WARNING("解析游戏数据updated_at时间戳失败: " + updated_at_str + ", 错误: " + std::string(e.what()));
                        game_data.updated_at = std::chrono::system_clock::now();
                    }
                } else {
                    game_data.updated_at = std::chrono::system_clock::now();
                }

                // 处理可选字段
                std::string last_played_str = result_set->getString("last_played_at");
                if (!last_played_str.empty() && last_played_str != "NULL") {
                    try {
                        game_data.last_played_at = timestampToTimePoint(std::stoll(last_played_str));
                    } catch (const std::exception& e) {
                        LOG_WARNING("解析last_played_at时间戳失败: " + last_played_str + ", 错误: " + std::string(e.what()));
                        // last_played_at 保持为 nullopt
                    }
                }

                return game_data;

            } catch (const std::exception& e) {
                LOG_ERROR("构建游戏数据对象时发生异常: " + std::string(e.what()));
                // 返回一个默认的游戏数据对象
                GameUserData default_data;
                default_data.user_id = -1; // 标记为无效数据
                default_data.created_at = std::chrono::system_clock::now();
                default_data.updated_at = std::chrono::system_clock::now();
                return default_data;
            }
        }

        /**
         * @brief 删除用户（软删除）
         * @param user_id 用户ID
         * @return 删除成功返回true
         */
        bool UserRepository::deleteUser(int64_t user_id) {
            try {
                if (!mysql_pool_) {
                    return false;
                }

                // 使用 RAII 连接管理器，确保连接自动归还
                common::database::MySQLConnectionGuard conn_guard(*mysql_pool_);
                auto mysql_conn = conn_guard.get();
                if (!mysql_conn) {
                    return false;
                }

                // 软删除：更新状态为已删除
                std::string sql = "UPDATE users SET status = ?, updated_at = ? WHERE user_id = ?";
                auto stmt = mysql_conn->prepareStatement(sql);

                stmt->setInt(1, static_cast<int>(UserStatus::DELETED));
                stmt->setString(2, std::to_string(getCurrentTimestamp()));
                stmt->setString(3, std::to_string(user_id));

                int affected_rows = stmt->executeUpdate();

                if (affected_rows > 0) {
                    // 清除缓存
                    if (config_.enable_cache && redis_pool_) {
                        clearUserCache(user_id);
                    }

                    users_updated_++;
                    LOG_INFO("用户删除成功，用户ID: " + std::to_string(user_id));
                    return true;
                }

                return false;

            } catch (const std::exception& e) {
                LOG_ERROR("删除用户失败: " + std::string(e.what()));
                return false;
            }
        }

        /**
         * @brief 清除用户缓存
         * @param user_id 用户ID
         * @return 清除成功返回true
         */
        bool UserRepository::clearUserCache(int64_t user_id) {
            try {
                if (!redis_pool_) {
                    return false;
                }

                // 使用 RAII 连接管理器，确保连接自动归还
                common::database::RedisConnectionGuard conn_guard(*redis_pool_);
                auto redis_conn = conn_guard.get();
                if (!redis_conn) {
                    return false;
                }

                // 清除用户ID缓存
                std::string user_id_key = generateUserCacheKey(user_id);
                redis_conn->del(user_id_key);

                // 清除用户名和邮箱缓存（需要先获取用户信息）
                auto user_opt = findUserById(user_id, false); // 不使用缓存
                if (user_opt.has_value()) {
                    auto user = user_opt.value();

                    std::string username_key = generateUsernameCacheKey(user.username);
                    redis_conn->del(username_key);

                    std::string email_key = generateEmailCacheKey(user.email);
                    redis_conn->del(email_key);
                }

                return true;

            } catch (const std::exception& e) {
                LOG_ERROR("清除用户缓存时发生异常: " + std::string(e.what()));
                return false;
            }
        }

        /**
         * @brief 获取统计信息
         * @return 统计信息JSON对象
         */
        nlohmann::json UserRepository::getStatistics() const {
            nlohmann::json stats;

            stats["queries_executed"] = queries_executed_.load();
            stats["cache_hits"] = cache_hits_.load();
            stats["cache_misses"] = cache_misses_.load();
            stats["users_created"] = users_created_.load();
            stats["users_updated"] = users_updated_.load();
            stats["game_data_operations"] = game_data_operations_.load();

            // 计算缓存命中率
            uint64_t total_cache_requests = cache_hits_.load() + cache_misses_.load();
            if (total_cache_requests > 0) {
                double hit_rate = static_cast<double>(cache_hits_.load()) / total_cache_requests;
                stats["cache_hit_rate"] = hit_rate;
            } else {
                stats["cache_hit_rate"] = 0.0;
            }

            // 配置信息
            stats["config"] = {
                {"enable_cache", config_.enable_cache},
                {"default_cache_ttl", config_.default_cache_ttl.count()},
                {"user_cache_ttl", config_.user_cache_ttl.count()},
                {"game_data_cache_ttl", config_.game_data_cache_ttl.count()},
                {"max_batch_size", config_.max_batch_size},
                {"enable_async_operations", config_.enable_async_operations}
            };

            return stats;
        }

        // ==================== 辅助方法实现 ====================

        /**
         * @brief 加载用户角色
         * @param user_info 用户信息
         */
        void UserRepository::loadUserRoles(CoreUserInfo& user_info) {
            try {
                std::string sql = "SELECT role_name FROM user_roles WHERE user_id = ?";
                // 使用 RAII 连接管理器
                common::database::MySQLConnectionGuard conn_guard(*mysql_pool_);
                auto mysql_conn = conn_guard.get();
                if (!mysql_conn) {
                    return;
                }

                auto stmt = mysql_conn->prepareStatement(sql);
                stmt->setInt64(1, user_info.user_id);
                auto result_set = stmt->executeQuery();

                user_info.roles.clear();
                while (result_set->next()) {
                    user_info.roles.push_back(result_set->getString("role_name"));
                }

            } catch (const std::exception& e) {
                LOG_ERROR("加载用户角色时发生异常: " + std::string(e.what()));
            }
        }

        /**
         * @brief 加载用户元数据
         * @param user_info 用户信息
         */
        void UserRepository::loadUserMetadata(CoreUserInfo& user_info) {
            try {
                std::string sql = "SELECT meta_key, meta_value FROM user_metadata WHERE user_id = ?";
                // 使用 RAII 连接管理器
                common::database::MySQLConnectionGuard conn_guard(*mysql_pool_);
                auto mysql_conn = conn_guard.get();
                if (!mysql_conn) {
                    return;
                }

                auto stmt = mysql_conn->prepareStatement(sql);
                stmt->setInt64(1, user_info.user_id);
                auto result_set = stmt->executeQuery();

                user_info.metadata.clear();
                while (result_set->next()) {
                    std::string key = result_set->getString("meta_key");
                    std::string value = result_set->getString("meta_value");
                    user_info.metadata[key] = value;
                }

            } catch (const std::exception& e) {
                LOG_ERROR("加载用户元数据时发生异常: " + std::string(e.what()));
            }
        }

        /**
         * @brief 更新用户角色
         * @param user_info 用户信息
         */
        void UserRepository::updateUserRoles(const CoreUserInfo& user_info) {
            try {
                // 使用 RAII 连接管理器，确保连接自动归还
                common::database::MySQLConnectionGuard conn_guard(*mysql_pool_);
                auto mysql_conn = conn_guard.get();
                if (!mysql_conn) {
                    return;
                }

                // 删除现有角色
                auto delete_stmt = mysql_conn->prepareStatement("DELETE FROM user_roles WHERE user_id = ?");
                delete_stmt->setInt64(1, user_info.user_id);
                delete_stmt->executeUpdate();

                // 插入新角色
                auto insert_stmt = mysql_conn->prepareStatement("INSERT INTO user_roles (user_id, role_name) VALUES (?, ?)");
                for (const auto& role : user_info.roles) {
                    insert_stmt->setInt64(1, user_info.user_id);
                    insert_stmt->setString(2, role);
                    insert_stmt->executeUpdate();
                }

            } catch (const std::exception& e) {
                LOG_ERROR("更新用户角色时发生异常: " + std::string(e.what()));
            }
        }

        /**
         * @brief 更新用户元数据
         * @param user_info 用户信息
         */
        void UserRepository::updateUserMetadata(const CoreUserInfo& user_info) {
            try {
                // 使用 RAII 连接管理器，确保连接自动归还
                common::database::MySQLConnectionGuard conn_guard(*mysql_pool_);
                auto mysql_conn = conn_guard.get();
                if (!mysql_conn) {
                    return;
                }

                // 使用REPLACE语句更新元数据
                auto stmt = mysql_conn->prepareStatement(
                    "REPLACE INTO user_metadata (user_id, meta_key, meta_value) VALUES (?, ?, ?)"
                );

                for (const auto& meta : user_info.metadata) {
                    stmt->setInt64(1, user_info.user_id);
                    stmt->setString(2, meta.first);
                    stmt->setString(3, meta.second);
                    stmt->executeUpdate();
                }

            } catch (const std::exception& e) {
                LOG_ERROR("更新用户元数据时发生异常: " + std::string(e.what()));
            }
        }

        /**
         * @brief 加载游戏用户自定义数据
         * @param game_data 游戏用户数据
         */
        void UserRepository::loadGameUserCustomData(GameUserData& game_data) {
            try {
                std::string sql = "SELECT data_key, data_value FROM game_user_custom_data WHERE user_id = ? AND game_type = ?";
                // 使用 RAII 连接管理器，确保连接自动归还
                common::database::MySQLConnectionGuard conn_guard(*mysql_pool_);
                auto mysql_conn = conn_guard.get();
                if (!mysql_conn) {
                    return;
                }

                auto stmt = mysql_conn->prepareStatement(sql);
                stmt->setInt64(1, game_data.user_id);
                stmt->setInt(2, static_cast<int>(game_data.game_type));
                auto result_set = stmt->executeQuery();

                game_data.game_data.clear();
                while (result_set->next()) {
                    std::string key = result_set->getString("data_key");
                    std::string value = result_set->getString("data_value");
                    game_data.game_data[key] = value;
                }

            } catch (const std::exception& e) {
                LOG_ERROR("加载游戏用户自定义数据时发生异常: " + std::string(e.what()));
            }
        }

        /**
         * @brief 加载游戏用户成就
         * @param game_data 游戏用户数据
         */
        void UserRepository::loadGameUserAchievements(GameUserData& game_data) {
            try {
                std::string sql = "SELECT achievement_name, achieved_at FROM game_user_achievements WHERE user_id = ? AND game_type = ?";
                // 使用 RAII 连接管理器，确保连接自动归还
                common::database::MySQLConnectionGuard conn_guard(*mysql_pool_);
                auto mysql_conn = conn_guard.get();
                if (!mysql_conn) {
                    return;
                }

                auto stmt = mysql_conn->prepareStatement(sql);
                stmt->setInt64(1, game_data.user_id);
                stmt->setInt(2, static_cast<int>(game_data.game_type));
                auto result_set = stmt->executeQuery();

                game_data.achievements.clear();
                while (result_set->next()) {
                    std::string achievement = result_set->getString("achievement_name");
                    game_data.achievements.push_back(achievement);
                }

            } catch (const std::exception& e) {
                LOG_ERROR("加载游戏用户成就时发生异常: " + std::string(e.what()));
            }
        }

        /**
         * @brief 清除所有缓存
         * @return 清除成功返回true
         */
        bool UserRepository::clearAllCache() {
            try {
                if (!redis_pool_) {
                    return false;
                }

                // 使用 RAII 连接管理器，确保连接自动归还
                common::database::RedisConnectionGuard conn_guard(*redis_pool_);
                auto redis_conn = conn_guard.get();
                if (!redis_conn) {
                    return false;
                }

                // 清除所有用户相关的缓存键
                // 注意：这是一个危险操作，实际应该更精确地清除
                LOG_WARNING("清除所有用户缓存");

                // 这里应该实现更精确的缓存清除逻辑
                // 由于Redis接口限制，暂时返回true
                return true;

            } catch (const std::exception& e) {
                LOG_ERROR("清除所有缓存失败: " + std::string(e.what()));
                return false;
            }
        }

        /**
         * @brief 预热用户缓存
         * @param user_ids 用户ID列表
         * @return 预热成功的用户数量
         */
        int UserRepository::warmupUserCache(const std::vector<int64_t>& user_ids) {
            int warmed_count = 0;

            try {
                for (int64_t user_id : user_ids) {
                    auto user = findUserById(user_id, false); // 从数据库获取
                    if (user.has_value()) {
                        // 存储到缓存
                        std::string cache_key = generateUserCacheKey(user_id);
                        if (setUserToCache(cache_key, user.value(), std::chrono::seconds(3600))) {
                            warmed_count++;
                        }
                    }
                }



            } catch (const std::exception& e) {
                LOG_ERROR("预热用户缓存失败: " + std::string(e.what()));
            }

            return warmed_count;
        }

        /**
         * @brief 清除游戏数据缓存
         * @param user_id 用户ID
         * @param game_type 游戏类型
         * @return 清除成功返回true
         */
        bool UserRepository::clearGameDataCache(int64_t user_id, GameType game_type) {
            try {
                if (!redis_pool_) {
                    return false;
                }

                // 使用 RAII 连接管理器，确保连接自动归还
                common::database::RedisConnectionGuard conn_guard(*redis_pool_);
                auto redis_conn = conn_guard.get();
                if (!redis_conn) {
                    return false;
                }

                std::string cache_key = generateGameDataCacheKey(user_id, game_type);
                redis_conn->del(cache_key);

                LOG_DEBUG("游戏数据缓存清除成功: 用户ID=" + std::to_string(user_id) +
                         ", 游戏类型=" + std::to_string(static_cast<int>(game_type)));
                return true;

            } catch (const std::exception& e) {
                LOG_ERROR("清除游戏数据缓存失败: " + std::string(e.what()));
                return false;
            }
        }

        /**
         * @brief 开始事务
         * @return 事务成功开始返回true
         */
        bool UserRepository::beginTransaction() {
            try {
                if (!mysql_pool_) {
                    return false;
                }

                // 使用 RAII 连接管理器，确保连接自动归还
                common::database::MySQLConnectionGuard conn_guard(*mysql_pool_);
                auto mysql_conn = conn_guard.get();
                if (!mysql_conn) {
                    return false;
                }

                mysql_conn->setAutoCommit(false);
                LOG_DEBUG("数据库事务开始");
                return true;

            } catch (const std::exception& e) {
                LOG_ERROR("开始事务失败: " + std::string(e.what()));
                return false;
            }
        }

        /**
         * @brief 提交事务
         * @return 事务提交成功返回true
         */
        bool UserRepository::commitTransaction() {
            try {
                if (!mysql_pool_) {
                    return false;
                }

                // 使用 RAII 连接管理器，确保连接自动归还
                common::database::MySQLConnectionGuard conn_guard(*mysql_pool_);
                auto mysql_conn = conn_guard.get();
                if (!mysql_conn) {
                    return false;
                }

                mysql_conn->commit();
                mysql_conn->setAutoCommit(true);
                LOG_DEBUG("数据库事务提交");
                return true;

            } catch (const std::exception& e) {
                LOG_ERROR("提交事务失败: " + std::string(e.what()));
                return false;
            }
        }

        /**
         * @brief 回滚事务
         * @return 事务回滚成功返回true
         */
        bool UserRepository::rollbackTransaction() {
            try {
                if (!mysql_pool_) {
                    return false;
                }

                // 使用 RAII 连接管理器，确保连接自动归还
                common::database::MySQLConnectionGuard conn_guard(*mysql_pool_);
                auto mysql_conn = conn_guard.get();
                if (!mysql_conn) {
                    return false;
                }

                mysql_conn->rollback();
                mysql_conn->setAutoCommit(true);
                LOG_DEBUG("数据库事务回滚");
                return true;

            } catch (const std::exception& e) {
                LOG_ERROR("回滚事务失败: " + std::string(e.what()));
                return false;
            }
        }

        /**
         * @brief 重置统计信息
         */
        void UserRepository::resetStatistics() {
            queries_executed_ = 0;
            cache_hits_ = 0;
            cache_misses_ = 0;
            users_created_ = 0;
            users_updated_ = 0;
            game_data_operations_ = 0;
            LOG_INFO("用户仓库统计信息已重置");
        }

        /**
         * @brief 验证数据库连接
         * @return 连接有效返回true
         */
        bool UserRepository::validateDatabaseConnection() {
            try {
                if (!mysql_pool_) {
                    return false;
                }

                // 使用 RAII 连接管理器，确保连接自动归还
                common::database::MySQLConnectionGuard conn_guard(*mysql_pool_);
                auto mysql_conn = conn_guard.get();
                if (!mysql_conn) {
                    return false;
                }

                // 执行简单查询测试连接
                auto stmt = mysql_conn->prepareStatement("SELECT 1");
                auto result = stmt->executeQuery();

                return result && result->next();

            } catch (const std::exception& e) {
                LOG_ERROR("数据库连接验证失败: " + std::string(e.what()));
                return false;
            }
        }

        /**
         * @brief 验证缓存连接
         * @return 连接有效返回true
         */
        bool UserRepository::validateCacheConnection() {
            try {
                if (!redis_pool_) {
                    return false;
                }

                // 使用 RAII 连接管理器，确保连接自动归还
                common::database::RedisConnectionGuard conn_guard(*redis_pool_);
                auto redis_conn = conn_guard.get();
                if (!redis_conn) {
                    return false;
                }

                // 测试Redis连接
                return redis_conn->exists("test_connection_key");

            } catch (const std::exception& e) {
                LOG_ERROR("缓存连接验证失败: " + std::string(e.what()));
                return false;
            }
        }

        /**
         * @brief 批量查询用户
         * @param user_ids 用户ID列表
         * @param use_cache 是否使用缓存
         * @return 用户信息列表
         */
        std::vector<CoreUserInfo> UserRepository::findUsersByIds(const std::vector<int64_t>& user_ids, bool use_cache) {
            std::vector<CoreUserInfo> users;

            try {
                if (user_ids.empty()) {
                    return users;
                }

                // 如果启用缓存，先从缓存查找
                std::vector<int64_t> cache_miss_ids;

                if (use_cache && config_.enable_cache && redis_pool_) {
                    for (int64_t user_id : user_ids) {
                        std::string cache_key = generateUserCacheKey(user_id);
                        auto cached_user = getUserFromCache(cache_key);
                        if (cached_user.has_value()) {
                            users.push_back(cached_user.value());
                            cache_hits_++;
                        } else {
                            cache_miss_ids.push_back(user_id);
                            cache_misses_++;
                        }
                    }
                } else {
                    cache_miss_ids = user_ids;
                }

                // 从数据库查询缓存未命中的用户
                if (!cache_miss_ids.empty()) {
                    std::string placeholders;
                    std::vector<std::string> params;

                    for (size_t i = 0; i < cache_miss_ids.size(); ++i) {
                        if (i > 0) placeholders += ",";
                        placeholders += "?";
                        params.push_back(std::to_string(cache_miss_ids[i]));
                    }

                    std::string sql = "SELECT * FROM users WHERE user_id IN (" + placeholders + ") AND status != ?";
                    params.push_back(std::to_string(static_cast<int>(UserStatus::DELETED)));

                    auto db_users = queryUsersFromDB(sql, params);

                    // 将查询结果存入缓存
                    if (use_cache && config_.enable_cache && redis_pool_) {
                        for (const auto& user : db_users) {
                            std::string cache_key = generateUserCacheKey(user.user_id);
                            setUserToCache(cache_key, user, config_.user_cache_ttl);
                        }
                    }

                    users.insert(users.end(), db_users.begin(), db_users.end());
                }

                queries_executed_++;

            } catch (const std::exception& e) {
                LOG_ERROR("批量查询用户失败: " + std::string(e.what()));
            }

            return users;
        }

        /**
         * @brief 条件查询用户
         * @param options 查询选项
         * @return 用户信息列表
         */
        std::vector<CoreUserInfo> UserRepository::findUsers(const QueryOptions& options) {
            std::vector<CoreUserInfo> users;

            try {
                if (!mysql_pool_) {
                    return users;
                }

                // 构建SQL查询
                std::string sql = "SELECT * FROM users";
                std::string where_clause = options.buildWhereClause();

                if (!where_clause.empty()) {
                    sql += " WHERE " + where_clause;
                }

                // 添加排序
                if (!options.order_by.empty()) {
                    sql += " ORDER BY " + options.order_by + " " + options.order_direction;
                }

                // 添加限制
                if (options.limit > 0) {
                    sql += " LIMIT " + std::to_string(options.limit);
                    if (options.offset > 0) {
                        sql += " OFFSET " + std::to_string(options.offset);
                    }
                }

                // 构建参数列表
                std::vector<std::string> params;
                for (const auto& condition : options.conditions) {
                    params.push_back(condition.value);
                }

                users = queryUsersFromDB(sql, params);
                queries_executed_++;

            } catch (const std::exception& e) {
                LOG_ERROR("条件查询用户失败: " + std::string(e.what()));
            }

            return users;
        }

        /**
         * @brief 从数据库查询多个用户
         * @param sql SQL语句
         * @param params 参数列表
         * @return 用户信息列表
         */
        std::vector<CoreUserInfo> UserRepository::queryUsersFromDB(const std::string& sql, const std::vector<std::string>& params) {
            std::vector<CoreUserInfo> users;

            try {
                if (!mysql_pool_) {
                    return users;
                }

                // 使用 RAII 连接管理器，确保连接自动归还
                common::database::MySQLConnectionGuard conn_guard(*mysql_pool_);
                auto mysql_conn = conn_guard.get();
                if (!mysql_conn) {
                    return users;
                }

                auto stmt = mysql_conn->prepareStatement(sql);

                // 设置参数
                for (size_t i = 0; i < params.size(); ++i) {
                    stmt->setString(static_cast<int>(i + 1), params[i]);
                }

                auto result_set = stmt->executeQuery();

                while (result_set && result_set->next()) {
                    CoreUserInfo user = buildUserFromResultSet(result_set);

                    // 加载用户角色和元数据
                    loadUserRoles(user);
                    loadUserMetadata(user);

                    users.push_back(user);
                }

            } catch (const std::exception& e) {
                LOG_ERROR("从数据库查询多个用户失败: " + std::string(e.what()));
            }

            return users;
        }

        /**
         * @brief 统计用户数量
         * @param options 查询选项
         * @return 用户数量
         */
        int64_t UserRepository::countUsers(const QueryOptions& options) {
            try {
                if (!mysql_pool_) {
                    return 0;
                }

                // 使用 RAII 连接管理器，确保连接自动归还
                common::database::MySQLConnectionGuard conn_guard(*mysql_pool_);
                auto mysql_conn = conn_guard.get();
                if (!mysql_conn) {
                    return 0;
                }

                // 构建COUNT查询
                std::string sql = "SELECT COUNT(*) FROM users";
                std::string where_clause = options.buildWhereClause();

                if (!where_clause.empty()) {
                    sql += " WHERE " + where_clause;
                }

                auto stmt = mysql_conn->prepareStatement(sql);

                // 设置参数
                int param_index = 1;
                for (const auto& condition : options.conditions) {
                    stmt->setString(param_index++, condition.value);
                }

                auto result_set = stmt->executeQuery();

                if (result_set && result_set->next()) {
                    queries_executed_++;
                    return result_set->getInt64(1);
                }

                return 0;

            } catch (const std::exception& e) {
                LOG_ERROR("统计用户数量失败: " + std::string(e.what()));
                return 0;
            }
        }

        /**
         * @brief 创建游戏用户数据
         * @param game_data 游戏用户数据
         * @return 创建成功返回true
         */
        bool UserRepository::createGameUserData(const GameUserData& game_data) {
            try {
                if (!mysql_pool_) {
                    return false;
                }

                // 验证和修正时间字段，防止无效的时间值导致数据库错误
                GameUserData corrected_data = game_data;
                auto epoch_time = std::chrono::system_clock::time_point{};
                auto current_time = std::chrono::system_clock::now();
                
                // 如果 last_played_at 是默认时间点（Unix epoch），设置为当前时间
                if (corrected_data.last_played_at == epoch_time) {
                    corrected_data.last_played_at = current_time;
                    LOG_DEBUG("修正 last_played_at 时间字段为当前时间");
                }
                
                // 确保 created_at 和 updated_at 不是默认时间点
                if (corrected_data.created_at == epoch_time) {
                    corrected_data.created_at = current_time;
                }
                if (corrected_data.updated_at == epoch_time) {
                    corrected_data.updated_at = current_time;
                }

                // 使用 RAII 连接管理器，确保连接自动归还
                common::database::MySQLConnectionGuard conn_guard(*mysql_pool_);
                auto mysql_conn = conn_guard.get();
                if (!mysql_conn) {
                    return false;
                }

                std::string sql = "INSERT INTO game_user_data (user_id, game_type, level, experience, coins, "
                                 "gems, total_games, wins, losses, draws, total_playtime_seconds, best_score, "
                                 "last_played_at, created_at, updated_at) "
                                 "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";

                auto stmt = mysql_conn->prepareStatement(sql);

                stmt->setString(1, std::to_string(corrected_data.user_id));
                stmt->setInt(2, static_cast<int>(corrected_data.game_type));
                stmt->setInt(3, corrected_data.level);
                stmt->setString(4, std::to_string(corrected_data.experience));
                stmt->setString(5, std::to_string(corrected_data.coins));
                stmt->setString(6, std::to_string(corrected_data.gems));
                stmt->setString(7, std::to_string(corrected_data.total_games));
                stmt->setString(8, std::to_string(corrected_data.wins));
                stmt->setString(9, std::to_string(corrected_data.losses));
                stmt->setString(10, std::to_string(corrected_data.draws));
                stmt->setString(11, std::to_string(corrected_data.total_playtime_seconds));
                stmt->setString(12, std::to_string(corrected_data.best_score));
                stmt->setString(13, timePointToMySQLDateTime(corrected_data.last_played_at));
                stmt->setString(14, timePointToMySQLDateTime(corrected_data.created_at));
                stmt->setString(15, timePointToMySQLDateTime(corrected_data.updated_at));

                int affected_rows = stmt->executeUpdate();

                if (affected_rows > 0) {
                    // 清除缓存
                    if (config_.enable_cache && redis_pool_) {
                        clearGameDataCache(game_data.user_id, game_data.game_type);
                    }

                    game_data_operations_++;

                    return true;
                }

                return false;

            } catch (const std::exception& e) {
                LOG_ERROR("创建游戏用户数据失败: " + std::string(e.what()));
                return false;
            }
        }

        /**
         * @brief 更新游戏用户数据
         * @param game_data 游戏用户数据
         * @return 更新成功返回true
         */
        bool UserRepository::updateGameUserData(const GameUserData& game_data) {
            try {
                if (!mysql_pool_) {
                    return false;
                }

                // 使用 RAII 连接管理器，确保连接自动归还
                common::database::MySQLConnectionGuard conn_guard(*mysql_pool_);
                auto mysql_conn = conn_guard.get();
                if (!mysql_conn) {
                    return false;
                }

                std::string sql = "UPDATE game_user_data SET level = ?, experience = ?, coins = ?, "
                                 "gems = ?, total_games = ?, wins = ?, losses = ?, draws = ?, "
                                 "total_playtime_seconds = ?, best_score = ?, last_played_at = ?, "
                                 "updated_at = ? WHERE user_id = ? AND game_type = ?";

                auto stmt = mysql_conn->prepareStatement(sql);

                stmt->setInt(1, game_data.level);
                stmt->setString(2, std::to_string(game_data.experience));
                stmt->setString(3, std::to_string(game_data.coins));
                stmt->setString(4, std::to_string(game_data.gems));
                stmt->setString(5, std::to_string(game_data.total_games));
                stmt->setString(6, std::to_string(game_data.wins));
                stmt->setString(7, std::to_string(game_data.losses));
                stmt->setString(8, std::to_string(game_data.draws));
                stmt->setString(9, std::to_string(game_data.total_playtime_seconds));
                stmt->setString(10, std::to_string(game_data.best_score));
                stmt->setString(11, timePointToMySQLDateTime(game_data.last_played_at));
                stmt->setString(12, timePointToMySQLDateTime(game_data.updated_at));
                stmt->setString(13, std::to_string(game_data.user_id));
                stmt->setInt(14, static_cast<int>(game_data.game_type));

                int affected_rows = stmt->executeUpdate();

                if (affected_rows > 0) {
                    // 清除缓存
                    if (config_.enable_cache && redis_pool_) {
                        clearGameDataCache(game_data.user_id, game_data.game_type);
                    }

                    game_data_operations_++;

                    return true;
                }

                return false;

            } catch (const std::exception& e) {
                LOG_ERROR("更新游戏用户数据失败: " + std::string(e.what()));
                return false;
            }
        }

        /**
         * @brief 获取用户所有游戏数据
         * @param user_id 用户ID
         * @param use_cache 是否使用缓存
         * @return 游戏用户数据列表
         */
        std::vector<GameUserData> UserRepository::getAllUserGameData(int64_t user_id, bool use_cache) {
            (void)use_cache;  // 消除未使用参数警告
            std::vector<GameUserData> game_data_list;

            try {
                if (!mysql_pool_) {
                    return game_data_list;
                }

                // 使用 RAII 连接管理器，确保连接自动归还
                common::database::MySQLConnectionGuard conn_guard(*mysql_pool_);
                auto mysql_conn = conn_guard.get();
                if (!mysql_conn) {
                    return game_data_list;
                }

                std::string sql = "SELECT * FROM game_user_data WHERE user_id = ?";
                auto stmt = mysql_conn->prepareStatement(sql);
                stmt->setString(1, std::to_string(user_id));

                auto result_set = stmt->executeQuery();

                while (result_set && result_set->next()) {
                    GameUserData game_data = buildGameDataFromResultSet(result_set);

                    // 加载自定义数据和成就
                    loadGameUserCustomData(game_data);
                    loadGameUserAchievements(game_data);

                    game_data_list.push_back(game_data);
                }

                queries_executed_++;

            } catch (const std::exception& e) {
                LOG_ERROR("获取用户所有游戏数据失败: " + std::string(e.what()));
            }

            return game_data_list;
        }

        /**
         * @brief 删除游戏用户数据
         * @param user_id 用户ID
         * @param game_type 游戏类型
         * @return 删除成功返回true
         */
        bool UserRepository::deleteGameUserData(int64_t user_id, GameType game_type) {
            try {
                if (!mysql_pool_) {
                    return false;
                }

                // 使用 RAII 连接管理器，确保连接自动归还
                common::database::MySQLConnectionGuard conn_guard(*mysql_pool_);
                auto mysql_conn = conn_guard.get();
                if (!mysql_conn) {
                    return false;
                }

                std::string sql = "DELETE FROM game_user_data WHERE user_id = ? AND game_type = ?";
                auto stmt = mysql_conn->prepareStatement(sql);

                stmt->setString(1, std::to_string(user_id));
                stmt->setInt(2, static_cast<int>(game_type));

                int affected_rows = stmt->executeUpdate();

                if (affected_rows > 0) {
                    // 清除缓存
                    if (config_.enable_cache && redis_pool_) {
                        clearGameDataCache(user_id, game_type);
                    }

                    game_data_operations_++;

                    return true;
                }

                return false;

            } catch (const std::exception& e) {
                LOG_ERROR("删除游戏用户数据失败: " + std::string(e.what()));
                return false;
            }
        }

        /**
         * @brief 批量更新游戏用户数据
         * @param game_data_list 游戏用户数据列表
         * @return 批量操作结果
         */
        BatchOperationResult UserRepository::batchUpdateGameUserData(const std::vector<GameUserData>& game_data_list) {
            auto start_time = std::chrono::steady_clock::now();

            try {
                if (!mysql_pool_ || game_data_list.empty()) {
                    return BatchOperationResult({"数据库连接无效或数据列表为空"});
                }

                // 使用 RAII 连接管理器，确保连接自动归还
                common::database::MySQLConnectionGuard conn_guard(*mysql_pool_);
                auto mysql_conn = conn_guard.get();
                if (!mysql_conn) {
                    return BatchOperationResult({"无法获取数据库连接"});
                }

                // 开始事务
                mysql_conn->setAutoCommit(false);

                std::string sql = "UPDATE game_user_data SET level = ?, experience = ?, coins = ?, "
                                 "gems = ?, total_games = ?, wins = ?, losses = ?, draws = ?, "
                                 "total_playtime_seconds = ?, best_score = ?, last_played_at = ?, "
                                 "updated_at = ? WHERE user_id = ? AND game_type = ?";

                auto stmt = mysql_conn->prepareStatement(sql);

                int affected_rows = 0;
                std::vector<std::string> errors;

                for (const auto& game_data : game_data_list) {
                    try {
                        stmt->setInt(1, game_data.level);
                        stmt->setString(2, std::to_string(game_data.experience));
                        stmt->setString(3, std::to_string(game_data.coins));
                        stmt->setString(4, std::to_string(game_data.gems));
                        stmt->setString(5, std::to_string(game_data.total_games));
                        stmt->setString(6, std::to_string(game_data.wins));
                        stmt->setString(7, std::to_string(game_data.losses));
                        stmt->setString(8, std::to_string(game_data.draws));
                        stmt->setString(9, std::to_string(game_data.total_playtime_seconds));
                        stmt->setString(10, std::to_string(game_data.best_score));
                        stmt->setString(11, timePointToMySQLDateTime(game_data.last_played_at));
                        stmt->setString(12, timePointToMySQLDateTime(game_data.updated_at));
                        stmt->setString(13, std::to_string(game_data.user_id));
                        stmt->setInt(14, static_cast<int>(game_data.game_type));

                        affected_rows += stmt->executeUpdate();

                    } catch (const std::exception& e) {
                        errors.push_back("用户ID " + std::to_string(game_data.user_id) +
                                       " 游戏类型 " + std::to_string(static_cast<int>(game_data.game_type)) +
                                       ": " + e.what());
                    }
                }

                // 提交事务
                mysql_conn->commit();
                mysql_conn->setAutoCommit(true);

                auto end_time = std::chrono::steady_clock::now();
                auto execution_time = std::chrono::duration_cast<std::chrono::milliseconds>(end_time - start_time);

                game_data_operations_ += affected_rows;

                if (errors.empty()) {
                    return BatchOperationResult(affected_rows, execution_time);
                } else {
                    BatchOperationResult result(errors);
                    result.affected_rows = affected_rows;
                    result.execution_time = execution_time;
                    return result;
                }

            } catch (const std::exception& e) {
                // 回滚事务 - 注意：由于使用了RAII管理器，连接会在作用域结束时自动归还
                // 这里的回滚操作会在同一个连接上执行
                try {
                    // 使用 RAII 连接管理器，确保连接自动归还
                    common::database::MySQLConnectionGuard conn_guard(*mysql_pool_);
                    auto mysql_conn = conn_guard.get();
                    if (mysql_conn) {
                        mysql_conn->rollback();
                        mysql_conn->setAutoCommit(true);
                    }
                } catch (...) {
                    // 忽略回滚错误
                }

                auto end_time = std::chrono::steady_clock::now();
                auto execution_time = std::chrono::duration_cast<std::chrono::milliseconds>(end_time - start_time);

                BatchOperationResult result({"批量更新失败: " + std::string(e.what())});
                result.execution_time = execution_time;
                return result;
            }
        }

        /**
         * @brief 获取缓存统计信息
         * @return 缓存统计信息
         */
        nlohmann::json UserRepository::getCacheStatistics() {
            nlohmann::json stats;

            try {
                stats["cache_enabled"] = config_.enable_cache;
                stats["cache_hits"] = cache_hits_.load();
                stats["cache_misses"] = cache_misses_.load();

                if (cache_hits_.load() + cache_misses_.load() > 0) {
                    double hit_rate = static_cast<double>(cache_hits_.load()) /
                                     (cache_hits_.load() + cache_misses_.load()) * 100.0;
                    stats["cache_hit_rate"] = hit_rate;
                } else {
                    stats["cache_hit_rate"] = 0.0;
                }

                stats["default_cache_ttl"] = config_.default_cache_ttl.count();
                stats["user_cache_ttl"] = config_.user_cache_ttl.count();
                stats["game_data_cache_ttl"] = config_.game_data_cache_ttl.count();

                // Redis连接状态
                if (redis_pool_) {
                    stats["redis_available"] = validateCacheConnection();
                } else {
                    stats["redis_available"] = false;
                }

            } catch (const std::exception& e) {
                LOG_ERROR("获取缓存统计信息失败: " + std::string(e.what()));
                stats["error"] = e.what();
            }

            return stats;
        }

        /**
         * @brief 获取总用户数
         * @return 总注册用户数
         */
        int64_t UserRepository::getTotalUserCount() const {
            try {
                QueryOptions options; // 空的查询选项，表示统计所有用户
                return const_cast<UserRepository*>(this)->countUsers(options);
            } catch (const std::exception& e) {
                LOG_ERROR("获取总用户数失败: " + std::string(e.what()));
                return 0;
            }
        }

        /**
         * @brief 获取健康状态
         * @return 健康状态信息
         */
        nlohmann::json UserRepository::getHealthStatus() const {
            nlohmann::json health;

            try {
                // 数据库连接状态
                health["database"]["available"] = (mysql_pool_ != nullptr);
                if (mysql_pool_) {
                    health["database"]["connected"] = true;
                }

                // 缓存连接状态
                health["cache"]["available"] = (redis_pool_ != nullptr);
                if (redis_pool_) {
                    health["cache"]["connected"] = true;
                }

                // 线程池状态
                health["thread_pool"]["available"] = (thread_pool_ != nullptr);

                // 配置状态
                health["config"]["cache_enabled"] = config_.enable_cache;
                health["config"]["async_enabled"] = config_.enable_async_operations;
                health["config"]["read_write_split"] = config_.enable_read_write_split;

                // 统计信息
                health["statistics"]["queries_executed"] = queries_executed_.load();
                health["statistics"]["users_created"] = users_created_.load();
                health["statistics"]["users_updated"] = users_updated_.load();
                health["statistics"]["game_data_operations"] = game_data_operations_.load();

                // 整体健康状态
                bool overall_healthy = (mysql_pool_ != nullptr);
                health["healthy"] = overall_healthy;

            } catch (const std::exception& e) {
                LOG_ERROR("获取健康状态失败: " + std::string(e.what()));
                health["healthy"] = false;
                health["error"] = e.what();
            }

            return health;
        }

    } // namespace auth_service
} // namespace core_services
